package com.cuixichang.minimalism.core.exception.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.cuixichang.minimalism.basal.base.Result;
import com.cuixichang.minimalism.basal.enums.ResponseCoderEnum;
import com.cuixichang.minimalism.basal.exceptions.AuthSecurityException;
import com.cuixichang.minimalism.basal.exceptions.CheckException;
import com.cuixichang.minimalism.basal.exceptions.NoDataException;
import com.cuixichang.minimalism.basal.exceptions.ServiceException;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Optional;

@ControllerAdvice
@Order(-1)
public class ExceptionHandlerGlobal {
    private static final Log log = LogFactory.get();
    /**
     * 系统主动抛出,Bean校验异常(请求说明可控)
     */
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public Result<String> validException(BindException e) {
        //解析原错误信息，封装后返回，此处返回非法的字段名称，错误信息
        Optional<String> optional = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage).findFirst();
        String message = ResponseCoderEnum.NotValidException.getDesc();
        if(optional.isPresent()) message = optional.get();
        return Result.error(ResponseCoderEnum.NotValidException.getCode(),message);
    }

    /**
     * 方法参数校验异常，可控异常信息
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result validException(MethodArgumentNotValidException e) {
        //解析原错误信息，封装后返回，此处返回非法的字段名称，错误信息
        Optional<String> optional = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage).findFirst();
        String message = ResponseCoderEnum.NotValidException.getDesc();
        if(optional.isPresent()) message = optional.get();
        return Result.error(ResponseCoderEnum.NotValidException.getCode(),message);
    }

    /**
     * 自定义抛出认证异常，消息准确
     */
    @ExceptionHandler(CheckException.class)
    @ResponseBody
    public Result checkException(CheckException checkException) {
        String message = checkException.getMessage();
        if(StrUtil.isBlank(message)) message = ResponseCoderEnum.CheckException.getDesc();
        return Result.error(ResponseCoderEnum.CheckException.getCode(),message);
    }

    /**
     * 拦截断言信息
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result paramCheckException(IllegalArgumentException e) {
        String message = e.getMessage();
        if (StrUtil.isBlank(message)) message = ResponseCoderEnum.NotValidException.getDesc();
        return Result.error(ResponseCoderEnum.NotValidException.getCode(), message);
    }

    /**
     * 应该存在数据区域却不存在情况
     */
    @ExceptionHandler(NoDataException.class)
    @ResponseBody
    public Result noDataException(NoDataException noDataException) {
        String message = noDataException.getMessage();
        if(StrUtil.isBlank(message)) message = ResponseCoderEnum.NoDataException.getDesc();
        return Result.error(ResponseCoderEnum.NoDataException.getCode(),message);
    }

    /**
     * 业务逻辑异常，消息准确
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Result serviceException(ServiceException serviceException) {
        log.error(serviceException);
        String message = serviceException.getMessage();
        if(StrUtil.isBlank(message)) message = ResponseCoderEnum.ServiceException.getDesc();
        return Result.error(ResponseCoderEnum.ServiceException.getCode(),message);
    }

    /**
     * 授权不通过,需要修改用户权限
     */
    @ExceptionHandler(AuthSecurityException.class)
    @ResponseBody
    public Result authSecurityException(AuthSecurityException authSecurityException) {
        log.error(authSecurityException);
        String message = authSecurityException.getMessage();
        if(StrUtil.isBlank(message)) message = ResponseCoderEnum.AccessDenied.getDesc();
        return Result.error(ResponseCoderEnum.AccessDenied.getCode(),message);
    }

    /**
     * 请求方法不存在,方法未创建
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result methodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return Result.error(ResponseCoderEnum.MethodNotSupportedException.getCode(),
                ResponseCoderEnum.MethodNotSupportedException.getDesc());
    }

    /**
     * 全局未知异常捕获
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception exception) throws Exception {
        Package aPackage = exception.getClass().getPackage();
        if(StrUtil.contains(aPackage.getName(),"org.springframework.security")){
            // 安全认证类下的异常不进行捕获
            throw exception;
        }else {
            log.error(exception);
            return Result.error(ResponseCoderEnum.Failed.getCode(), ResponseCoderEnum.Failed.getDesc());
        }
    }
}
